import { queryActivities, queryActivityDetail, saveActivity, changeActivityStatus, deleteActivity } from '../services/api';
import { message } from 'antd';

export default {
  namespace: 'activities',

  state: {
    data: {},
  },

  effects: {
    *fetchList({ payload }, { call, put }) {
      const response = yield call(queryActivities, payload);
      if(response){
        yield put({
          type: 'save',
          payload: {
            data : response
          }
        });

      }
    },
    *changeStatus({ payload }, { call, put }){  //活动状态
      const res = yield call(changeActivityStatus, payload);
      if(res){
        yield put({
          type : 'saveStatus',
          payload : payload
        });
        message.success('成功');
      }
    },
    *deleteItem({ payload }, { call, put }){  //删除活动
      const res = yield call(deleteActivity, payload);
      if(res){
        yield put({
          type : 'saveDelete',
          payload : payload
        });
      }
    },
    *getDetail({ payload }, { call, put }){  //详情
      const res = yield call(queryActivityDetail, payload);
      if(res){
        // yield put({
        //   type : 'save',
        //   payload : {data : res}
        // });
        return res;
      }
    },
    *saveActivity({ payload }, { call, put }) {
      const res = yield call(saveActivity, payload);
      if(res){

        message.success(payload.id ? '修改成功' : '新增成功！');
        //yield put(routerRedux.push(`/goods/goods-add?id=${res.id}`));
        return res;
        setTimeout(function(){
          window.location.reload(true);
        },2000);
      }
    },
  },

  reducers: {
    save(state, {payload}){
      return {
        ...state,
        ...payload
      }
    },
    saveStatus(state, { payload }){
      let data = {...state.data};
      data.list.forEach((v,i)=>{
        if(v.id == payload.id){
          data.list[i].status = payload.status;  //修改为结束状态
        }
      });
      return {
        ...state,
        ...{data:data}
      }
    },
    saveDelete(state, { payload }){
      let data = {...state.data};
      data.list.forEach((v,i)=>{
        if(v.id == payload.ids){
          data.list.splice(i,1);
        }
      });
      message.success('删除成功！');
      return {
        ...state,
        ...{data:data}
      }
    },
  }
};
